import os

import jwt
from django.utils.timezone import now
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.tokens import RefreshToken
from django.db.models import Q
from rest_framework import status

# 注册逻辑
from .models import Doctor
from django.contrib.auth.hashers import check_password
from .doctorRegisterForm import  DoctorRegisterForm
from django.contrib.auth.hashers import make_password
from django.conf import settings

from .DoctorUpdateSerializer import DoctorUpdateSerializer
# @require_http_methods(['GET', 'POST'])
# def account_register(request):
#     # class Doctor(models.Model):
#     #     doctor_name = models.CharField(max_length=100)  # 医生姓名
#     #     doctor_account = models.CharField(max_length=11)  # 医生账号
#     #     doctor_password = models.CharField(max_length=100)  # 医生密码
#     #     create_time = models.DateTimeField(auto_now_add=True)
#     #     about_me = models.CharField(max_length=255)  # 医生简介
#     #     age = models.IntegerField()
#     #     education = models.CharField(max_length=100)
#     #     major = models.CharField(max_length=50)
#     #     order_money = models.FloatField()
#     #     photo = models.CharField(max_length=255)
#     #     post_level = models.CharField(max_length=100)
#     #     subject_id = models.CharField(max_length=100)
#     #     subject_name = models.CharField(max_length=100)
#     #     university = models.CharField(max_length=100)  # 医生毕业学校
#     #     work_date = models.DateField()
#
#     # Doctor(doctor_name=doctor_name,doctor_account=doctor_account,doctor_password=doctor_password)
#     doctor = Doctor(doctor_name="龙傲天",doctor_account="123456",doctor_password="123456")
#     doctor.save()
#     # account = request.GET.get('account')
#     # password = request.GET.get('password')
#     # user = authenticate(request, username=username, password=password)
#     return HttpResponse(f"注册成功")


    # path('doctor/register', doctor_views.account_register),
    # path('doctor/login', doctor_views.account_login),
    # path('doctor/<int:doctor_id>', doctor_views.doctor_search),

# 医生注册逻辑
class DoctorAccountRegister(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def post(self, request):
        form = DoctorRegisterForm(request.data)  # 传递 request.data 到表单
        print("打印表单是否有效")
        print(form.is_valid)

        if form.is_valid():
            doctor_account = form.cleaned_data['doctor_account']
            doctor_password = form.cleaned_data['doctor_password']

            # 使用 make_password 加密密码
            hashed_password = make_password(doctor_password)

            # 创建新的 Patient 记录
            print("写入数据库")
            Doctor.objects.create(doctor_account=doctor_account, doctor_password=hashed_password)

            # 返回成功响应
            return Response({"message": f"注册成功, 账号为：{doctor_account}"}, status=200)
        else:
            return Response({"message": "注册失败"}, status=400)


# 医生登录逻辑
class DoctorAccountLogin(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def post(self, request):
        doctor_account = request.data.get('doctor_account')  # 从请求中获取手机号
        doctor_password = request.data.get('doctor_password')  # 从请求中获取密码

        try:
            # 通过手机号查找患者记录
            doctor = Doctor.objects.get(doctor_account=doctor_account)
        except Doctor.DoesNotExist:
            return Response({"message": "医生账号不存在"}, status=400)

        # 使用 check_password 来验证密码是否正确
        if check_password(doctor_password, doctor.doctor_password):
            refresh = RefreshToken.for_user(doctor)
            access_token = str(refresh.access_token)

            # 返回生成的 token
            return Response({
                "message": "登录成功",
                "access_token": access_token,
                "refresh_token": str(refresh),
                "role": "doctor"
            }, status=200)
        else:
            # 如果密码错误
            return Response({"message": "密码错误"}, status=400)


class Get_Target(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def get(self, request):
        doctor_name = request.GET.get('doctor_name')
        doctor_subject_name = request.GET.get('subject_name')
        doctor_post_level = request.GET.get('post_level')
        doctor_work_date = request.GET.get('work_date')

        query = Q()

        # 根据传入的参数动态添加过滤条件
        if doctor_name:
            query &= Q(doctor_name=doctor_name)
        if doctor_subject_name:
            query &= Q(subject_name=doctor_subject_name)
        if doctor_post_level:
            query &= Q(post_level=doctor_post_level)
        if doctor_work_date:
            query &= Q(work_date=doctor_work_date)

        try:
            doctors = Doctor.objects.defer('doctor_account','doctor_password').filter(query)
            doctors_data = list(doctors.values('id','doctor_name', 'create_time', 'about_me', 'age', 'education','major','order_money','photo','post_level','subject_id','subject_name','university','work_date'))
        except Doctor.DoesNotExist:
            return Response({"error": "doctor not found"}, status=500)

        if doctors:
            return Response({'doctors': doctors_data}, status=200)

        return Response({"error": "doctor not found"}, status=500)

# def doctor_search(request, doctor_id):
#     # doctor_id = doctor_id
#     # doctor_id = Doctor.objects.get(id=doctor_id)
#     doctor = Doctor.objects.defer('doctor_account','doctor_password').get(id=doctor_id)
#     return HttpResponse(f"你好，查询成功,名字为：{doctor.doctor_name}")
#
# def doctor_search_all(request):
#     doctors = Doctor.objects.defer('doctor_account','doctor_password').all()
#     # 将医生数据转化为字典列表
#     doctors_data = list(doctors.values('id', 'doctor_name', 'create_time', 'about_me',
#                                        'age','education','major','order_money','photo',
#                                        'post_level','subject_id','subject_name',
#                                        'university','work_date'))
#
#     # 返回 JSON 格式的响应
#     return JsonResponse({'doctors': doctors_data})



class GetDoctorInfo(APIView):
    def get(self, request):
        # 获取前端传过来的token
        token = request.headers.get('Authorization', None)

        if not token:
            return Response({'error': '未提供Token'}, status=400)

        try:
            # 解码token，获取payload中的user_id
            # token = token.split(' ')[1]  # 去除 Bearer 部分
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
            doctor_id = payload.get('user_id')
            print("医生id为", doctor_id)



            if not doctor_id:
                return Response({'error': 'doctor_id not found in token'}, status=400)

            # 查询数据库，获取user_id对应的年龄
            try:
                doctor = Doctor.objects.get(id=doctor_id)
                photo_url = ""
                if doctor.photo and doctor.photo.name:
                    photo_url = doctor.photo.url
                return Response({'doctor_id': doctor_id, 'doctor_name': doctor.doctor_name,
                                 'gender':doctor.gender,'doctor_account':doctor.doctor_account,
                                 'about_me': doctor.about_me,'age':doctor.age,'education':doctor.education,
                                 'major':doctor.major,'post_level':doctor.post_level,
                                 'subject_id':doctor.subject_id,'subject_name':doctor.subject_name,
                                 'university':doctor.university,'work_date':doctor.work_date,"photo":photo_url}, status=200)
            except  Doctor.DoesNotExist:
                return Response({'error': '查无此人'}, status=404)

        except jwt.ExpiredSignatureError:
            return Response({'error': 'Token has expired,过期啦'}, status=401,)
        except jwt.InvalidTokenError:
            return Response({'error': 'Invalid token,无效'}, status=401)


class DoctorUpdate(APIView):
    def post(self, request):
        # 获取传入的 id，用来查找医生
        doctor_id = request.data.get("doctor_id")
        if not doctor_id:
            return Response({"detail": "id is required."}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 查找现有医生
            doctor = Doctor.objects.get(id=doctor_id)
        except Doctor.DoesNotExist:
            # 如果医生不存在，返回 404
            return Response({"detail": "Doctor not found."}, status=status.HTTP_404_NOT_FOUND)

        # 更新医生信息
        serializer = DoctorUpdateSerializer(doctor, data=request.data, partial=True)  # partial=True 允许部分更新
        if serializer.is_valid():
            serializer.save()  # 保存更新后的实例
            data ={
                "id": doctor_id,
                'doctor_name': doctor.doctor_name,
                'message': "更新成功"
            }

            return Response(data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class DoctorProfilePhoto(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def post(self, request, *args, **kwargs):
        doctor_id = request.data.get('doctor_id')
        # 获取上传的文件
        photo = request.FILES.get('photo')

        if not doctor_id:
            return Response({"error": "doctor_id is required"}, status=400)

        if not photo:
            return Response({"error": "photo is required"}, status=400)

        try:
            # 查找 Doctor 实例
            doctor = Doctor.objects.get(id=doctor_id)
        except Doctor.DoesNotExist:
            return Response({"error": "Doctor not found"}, status=400)
        if photo:
            doctor.photo = photo
            doctor.photo.name = doctor_profilephoto_upload_to(doctor, photo.name)
            doctor.save()

            # 可以返回新的Patient数据，也可以返回文件路径等信息
            return Response({
                "message": "图片上传成功",
                "photo": doctor.photo.url
                             }, status=200)
        return Response({"error": "No profile photo uploaded"}, status=400)


def doctor_profilephoto_upload_to(instance, filename):
    doctor_id = instance.id  # 获取 user_id
    ext = filename.split('.')[-1]  # 获取文件的扩展名
    new_filename = f"{doctor_id}_{now().strftime('%Y%m%d%H%M%S')}.{ext}"  # 文件名以 user_id + 时间戳命名
    return os.path.join('./', new_filename)  # 不要再加 'profile_photos/'，保持路径简洁
